package main

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/urfave/cli"
	"go-admin-auth/conf"
	"go-admin-auth/hgin/define"
	"os"
	"time"
)

var app = cli.NewApp()

func init() {
	app.Name = "admin"
	app.Usage = "go auth admin base service"
	app.Version = "v1.0.0"
	app.Flags = []cli.Flag{
	}
	app.Before = func(c *cli.Context) error {
		//logrus.SetLevel(logrus.InfoLevel)
		//if c.GlobalBool("verbose") {
		//	logrus.SetLevel(logrus.DebugLevel)
		//}
		return nil
	}

	app.Commands = append(app.Commands,
		cli.Command{
			Name:  "try",
			Usage: "try code",
			Action: func(c *cli.Context) error {
				fmt.Println("ss")
				return nil
			},
		},

		cli.Command{
			Name:  "inner-token",
			Usage: "generate inner token",
			Flags: []cli.Flag{
				cli.IntFlag{
					Name:  "systemId",
					Usage: "gen system token",
				},
			},
			Action: func(c *cli.Context) error {
				systemId := c.Int("systemId")
				fmt.Println("systemId is :", systemId)

				hmacSampleSecret := conf.GetEnvDft(define.InnerJwtSecretKey, "inner-jwt-secret")
				fmt.Println("hmacSampleSecret:", hmacSampleSecret)

				// 生成token https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac
				jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"system_id": systemId, "exp": time.Now().Unix() + 86400*30*10*10})

				token, _ := jwtToken.SignedString([]byte(hmacSampleSecret))
				fmt.Println(token)
				return nil
			},
		},

		cli.Command{
			Name:  "print-token",
			Usage: "print inner token",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "token",
					Usage: "print token",
				},
			},
			Action: func(c *cli.Context) error {
				tokenString := c.String("token")
				fmt.Println("token is :", tokenString)

				token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
					// Don't forget to validate the alg is what you expect:
					if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
						return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
					}

					hmacSampleSecret := conf.GetEnvDft(define.InnerJwtSecretKey, "inner-jwt-secret")
					// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
					return []byte(hmacSampleSecret), nil
				})

				if err != nil {
					fmt.Println(err)
				}

				fmt.Println(token)
				return nil
			},
		},


	)

}

func main() {
	app.Run(os.Args)
}
